package com.tepth.vehiclemaintenance.mvp.work;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.event.NFCEvent;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.tools.bleNfc.NFCInterface;
import com.tepth.vehiclemaintenance.tools.bleNfc.NFCManger;

import org.greenrobot.eventbus.EventBus;

import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NFCDialogActivity extends AppCompatActivity implements NFCInterface {

    public static final int NFC_RESULTCODE = 3;
    public static final int RETURN_BARCODE = 3;
    private static final int REQUEST_CODE_LOCATION = 2;
    @BindView(R.id.tv_message)
    TextView tv_message;

    @BindView(R.id.nfc_loading)
    RelativeLayout nfc_loading;

    @BindView(R.id.nfc_message)
    RelativeLayout nfc_message;

    @BindView(R.id.nfcdialog_title)
    TextView nfcdialog_title;

    @BindView(R.id.rl_nfc_listview)
    RelativeLayout rl_nfc_listview;

    @BindView(R.id.lv_nfc)
    ListView list_nfc;

    private Context context;
    private byte[] msgBuffer;
    private String address;
    private ArrayAdapter<String> mac_adapter;
    Vector<String> mNfcList = new Vector<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfcdialog);
        context = this;
        ButterKnife.bind(this);
        mac_adapter = new ArrayAdapter<>(this, R.layout.item_text, mNfcList);
        list_nfc.setAdapter(mac_adapter);


        //动态权限申请
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE_LOCATION);
        } else {
            setData();
        }


    }

    private void startNFCManger() {
        switch (NFCManger.isConnection()) {
            case 0:
                NFCManger.createDeviceManager(context, this);
                break;
            case 1:
                NFCManger.startGetDevice(this, context);
                break;
            case 2:
                NFCManger.startGetCard(this);
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://正在搜索设备
                    tv_message.setText("正在搜索设备...");
                    break;
                case 1://正在连接设备
                    tv_message.setText("正在连接设备...");
                    break;
                case 2://设备连接成功，准备打卡
                    tv_message.setText("设备连接成功");
                    break;
                case 7:
                    nfc_loading.setVisibility(View.VISIBLE);
                    nfc_message.setVisibility(View.GONE);
                    tv_message.setText("正在搜索卡片...");
                    break;
                case 3://打卡成功
//                    Intent result = new Intent();
//                    result.putExtra("BarCodeContents", msgBuffer);
//                    setResult(NFC_RESULTCODE, result);
                    EventBus.getDefault().post(new NFCEvent(msgBuffer,NFC_RESULTCODE));
                    finish();
                    break;
                case 4://设备连接中断，重新搜索设备
                    tv_message.setText("设备连接中断,重新搜索设备");
                    break;
                case 5://打开失败,请重新打卡
                    tv_message.setText("打卡失败,请重新打卡");
                    break;
                case 6:
                    nfc_loading.setVisibility(View.GONE);
                    nfc_message.setVisibility(View.VISIBLE);
                    break;
                case 8://读取到存储的MAC地址，更改标题栏
                    if (!address.equals(getString(R.string.unbind_device)))
                        nfcdialog_title.setText("已绑定设备：" + address);
                    else
                        nfcdialog_title.setText("未绑定设备，请选择一个NFC设备绑定");
                    break;
                case 9://显示NFC列表
                    Vector<String> nfcList = (Vector<String>) msg.getData().getSerializable("nfcList");
                    if (nfcList != null && !nfcList.isEmpty()) {
                        nfc_loading.setVisibility(View.GONE);
                        nfc_message.setVisibility(View.GONE);
                        rl_nfc_listview.setVisibility(View.VISIBLE);
                        mNfcList.clear();
                        mNfcList.addAll(nfcList);
                        mac_adapter.notifyDataSetChanged();
                    } else {
                        nfc_loading.setVisibility(View.VISIBLE);
                        nfc_message.setVisibility(View.GONE);
                        rl_nfc_listview.setVisibility(View.GONE);
                        tv_message.setText("正在搜索设备...");
                    }
                    break;
                case 10://隐藏NFC列表
                    nfc_loading.setVisibility(View.VISIBLE);
                    nfc_message.setVisibility(View.GONE);
                    rl_nfc_listview.setVisibility(View.GONE);
                    tv_message.setText("正在搜索设备...");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void searchDevice() {
        handler.sendEmptyMessage(0);
    }

    @Override
    public void connectionDevice() {
        handler.sendEmptyMessage(1);
    }

    @Override
    public void successConnectionDevice() {
        handler.sendEmptyMessage(2);
    }

    @Override
    public void searchCard() {
        handler.sendEmptyMessage(7);
    }

    @Override
    public void successCard(byte[] msgBuffer) {
        this.msgBuffer = msgBuffer;
        handler.sendEmptyMessage(3);
    }

    @Override
    public void errorCard() {
        handler.sendEmptyMessage(5);
    }

    @Override
    public void stopSearchCard() {
        handler.sendEmptyMessage(6);
    }

    @Override
    public void updateDeviceList(Vector<String> nfcList) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("nfcList", nfcList);
        Message msg = Message.obtain();
        msg.what = 9;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @OnClick({R.id.nfc_message, R.id.btn_barcode, R.id.btn_cancel})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.nfc_message:
                NFCManger.startGetCard(this);
                break;
            case R.id.btn_barcode:
                setResult(RETURN_BARCODE);
                NFCManger.setStopGetDevicedList(true);
                NFCManger.stopSearchCard();
                finish();
                break;
            case R.id.btn_cancel:
                NFCManger.setStopGetDevicedList(true);
                NFCManger.stopSearchCard();
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        NFCManger.setStopGetDevicedList(true);
        NFCManger.stopSearchCard();
        NFCManger.interruptDevice();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_LOCATION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    setData();
                } else {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void setData() {
        address = SPUtils.getString(this, SpKey.KEY_NFC_BIND_MAC, getString(R.string.unbind_device));
        if (address.equals(getString(R.string.unbind_device))) {
            NFCManger.startScanAndGetDevicedList(this, context);
        } else {
            startNFCManger();
        }

        handler.sendEmptyMessage(8);
        list_nfc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                address = mac_adapter.getItem(position);
                SPUtils.putString(NFCDialogActivity.this, SpKey.KEY_NFC_BIND_MAC, address);
                NFCManger.setStopGetDevicedList(true);
                startNFCManger();
                handler.sendEmptyMessage(8);
                handler.sendEmptyMessage(10);
            }
        });

    }

}
